import Mock from 'mockjs';

// 创建内存数据库
const mockDatabase = (() => {
  // 生成律师数据
  const generateLawyers = () => {
    return Mock.mock({
      'list|20-30': [
        {
          'id|+1': 1,
          'username': '@word(5, 10)',
          'name': '@cname',
          'email': '@email',
          'phone': /1[3-9]\d{9}/,
          'avatar': '@image("100x100", "#4A7BF7", "Lawyer")',
          'status|0-1': 0, // 0-正常, 1-禁用
          'gender|0-1': 0, // 0-男, 1-女
          'age|25-65': 35,
          'address': '@county(true)',
          'idCard': /[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]/,
          'licenseNumber': /[A-Z]{2}\d{6}/,
          'specialties|1-3': ['@pick(["民事纠纷", "刑事辩护", "劳动纠纷", "婚姻家事", "合同纠纷", "知识产权"])'],
          'experience|1-20': 5,
          'education': '@pick(["本科", "硕士", "博士"])',
          'lawSchool': '@pick(["北京大学法学院", "清华大学法学院", "中国人民大学法学院", "中国政法大学", "华东政法大学"])',
          'hourlyRate|100-500': 200,
          'rating|3-5': 4,
          'reviewCount|10-100': 50,
          'completedCases|10-200': 80,
          'currentCases|0-10': 5,
          'available|0-1': 1, // 0-忙碌, 1-空闲
          'bio': '@cparagraph(2, 4)',
          'achievements|0-5': [
            {
              'id|+1': 1,
              'title': '@ctitle(5, 15)',
              'description': '@csentence(10, 30)',
              'year|2010-2024': 2020
            }
          ],
          'certificates|0-3': [
            {
              'id|+1': 1,
              'name': '@pick(["律师执业证", "法律职业资格证", "专业领域证书"])',
              'issueDate': '@date("yyyy-MM-dd")',
              'expiryDate': '@date("yyyy-MM-dd")'
            }
          ],
          'createdAt': '@datetime',
          'lastLoginAt': '@datetime',
          'schedule': {
            'monday': { 'morning': true, 'afternoon': true, 'evening': false },
            'tuesday': { 'morning': true, 'afternoon': true, 'evening': false },
            'wednesday': { 'morning': true, 'afternoon': true, 'evening': false },
            'thursday': { 'morning': true, 'afternoon': true, 'evening': false },
            'friday': { 'morning': true, 'afternoon': true, 'evening': false },
            'saturday': { 'morning': false, 'afternoon': false, 'evening': false },
            'sunday': { 'morning': false, 'afternoon': false, 'evening': false }
          }
        }
      ]
    }).list;
  };

  return {
    lawyers: generateLawyers()
  };
})();

/**
 * 律师模块Mock配置
 * @param {MockAdapter} mock - Mock适配器实例
 */
export default function(mock) {
  // 获取律师列表（带分页和筛选）
  mock.onGet('/lawyers').reply(config => {
    const { 
      page = 1, 
      size = 10, 
      status, 
      specialty, 
      available,
      keyword,
      minRating,
      maxHourlyRate
    } = config.params;
    
    let filteredLawyers = [...mockDatabase.lawyers];
    
    // 状态筛选
    if (status !== undefined) {
      filteredLawyers = filteredLawyers.filter(l => l.status === parseInt(status));
    }
    
    // 专业领域筛选
    if (specialty) {
      filteredLawyers = filteredLawyers.filter(l => l.specialties.includes(specialty));
    }
    
    // 空闲状态筛选
    if (available !== undefined) {
      filteredLawyers = filteredLawyers.filter(l => l.available === parseInt(available));
    }
    
    // 最低评分筛选
    if (minRating) {
      filteredLawyers = filteredLawyers.filter(l => l.rating >= parseFloat(minRating));
    }
    
    // 最高时薪筛选
    if (maxHourlyRate) {
      filteredLawyers = filteredLawyers.filter(l => l.hourlyRate <= parseFloat(maxHourlyRate));
    }
    
    // 关键词搜索
    if (keyword) {
      filteredLawyers = filteredLawyers.filter(l => 
        l.name.includes(keyword) || 
        l.specialties.some(s => s.includes(keyword)) ||
        l.bio.includes(keyword)
      );
    }
    
    // 按评分和完成案件数排序
    filteredLawyers.sort((a, b) => {
      const scoreA = a.rating * 0.7 + (a.completedCases / 100) * 0.3;
      const scoreB = b.rating * 0.7 + (b.completedCases / 100) * 0.3;
      return scoreB - scoreA;
    });
    
    const start = (page - 1) * size;
    const end = start + size;
    const paginated = filteredLawyers.slice(start, end);
    
    return [200, {
      code: 200,
      data: paginated,
      pagination: {
        page: parseInt(page),
        size: parseInt(size),
        total: filteredLawyers.length,
        totalPages: Math.ceil(filteredLawyers.length / size)
      }
    }];
  });

  // 获取单个律师详情
  mock.onGet(/\/lawyers\/\d+$/).reply(config => {
    const lawyerId = config.url.split('/').pop();
    const lawyer = mockDatabase.lawyers.find(l => l.id == lawyerId);
    
    return lawyer 
      ? [200, { code: 200, data: lawyer }]
      : [404, { code: 404, message: '律师不存在' }];
  });

  // 创建律师
  mock.onPost('/lawyers').reply(config => {
    const newLawyer = JSON.parse(config.data);
    newLawyer.id = Math.max(...mockDatabase.lawyers.map(l => l.id)) + 1;
    newLawyer.createdAt = new Date().toISOString();
    newLawyer.status = 0; // 默认正常状态
    newLawyer.available = 1; // 默认空闲
    newLawyer.avatar = Mock.Random.image('100x100', '#4A7BF7', 'Lawyer');
    newLawyer.rating = 5; // 新律师默认5星
    newLawyer.reviewCount = 0;
    newLawyer.completedCases = 0;
    newLawyer.currentCases = 0;
    newLawyer.achievements = [];
    newLawyer.certificates = [];
    
    mockDatabase.lawyers.unshift(newLawyer);
    
    return [201, { 
      code: 201, 
      message: '律师创建成功',
      data: newLawyer
    }];
  });

  // 更新律师信息
  mock.onPut(/\/lawyers\/\d+$/).reply(config => {
    const lawyerId = config.url.split('/').pop();
    const updateData = JSON.parse(config.data);
    
    const lawyerIndex = mockDatabase.lawyers.findIndex(l => l.id == lawyerId);
    
    if (lawyerIndex === -1) {
      return [404, { code: 404, message: '律师不存在' }];
    }
    
    // 更新律师信息
    mockDatabase.lawyers[lawyerIndex] = {
      ...mockDatabase.lawyers[lawyerIndex],
      ...updateData,
      id: parseInt(lawyerId) // 确保ID不被修改
    };
    
    return [200, { 
      code: 200, 
      message: '律师信息更新成功',
      data: mockDatabase.lawyers[lawyerIndex]
    }];
  });

  // 删除律师
  mock.onDelete(/\/lawyers\/\d+$/).reply(config => {
    const lawyerId = config.url.split('/').pop();
    const lawyerIndex = mockDatabase.lawyers.findIndex(l => l.id == lawyerId);
    
    if (lawyerIndex === -1) {
      return [404, { code: 404, message: '律师不存在' }];
    }
    
    mockDatabase.lawyers.splice(lawyerIndex, 1);
    
    return [200, { 
      code: 200, 
      message: '律师删除成功' 
    }];
  });

  // 更新律师状态
  mock.onPatch(/\/lawyers\/\d+\/status/).reply(config => {
    const lawyerId = config.url.split('/').pop();
    const { status } = JSON.parse(config.data);
    
    const lawyer = mockDatabase.lawyers.find(l => l.id == lawyerId);
    
    if (!lawyer) {
      return [404, { code: 404, message: '律师不存在' }];
    }
    
    lawyer.status = status;
    
    return [200, { 
      code: 200, 
      message: '律师状态更新成功',
      data: lawyer
    }];
  });

  // 更新律师可用状态
  mock.onPatch(/\/lawyers\/\d+\/availability/).reply(config => {
    const lawyerId = config.url.split('/').pop();
    const { available } = JSON.parse(config.data);
    
    const lawyer = mockDatabase.lawyers.find(l => l.id == lawyerId);
    
    if (!lawyer) {
      return [404, { code: 404, message: '律师不存在' }];
    }
    
    lawyer.available = available;
    
    return [200, { 
      code: 200, 
      message: '律师可用状态更新成功',
      data: lawyer
    }];
  });

  // 获取律师工作台数据
  mock.onGet(/\/lawyers\/\d+\/dashboard/).reply(config => {
    const lawyerId = config.url.split('/').pop();
    const lawyer = mockDatabase.lawyers.find(l => l.id == lawyerId);
    
    if (!lawyer) {
      return [404, { code: 404, message: '律师不存在' }];
    }
    
    // 模拟该律师的案件数据
    const todayCases = Mock.mock({
      'list|0-5': [
        {
          'id|+1': 1000,
          'title': '@ctitle(10, 20)',
          'status|0-2': 1,
          'priority|0-2': 1,
          'scheduledTime': '@datetime',
          'duration|30-120': 60
        }
      ]
    }).list;
    
    const weeklyStats = {
      totalCases: lawyer.currentCases,
      completedCases: Math.floor(lawyer.currentCases * 0.3),
      pendingCases: Math.floor(lawyer.currentCases * 0.7),
      totalHours: Math.floor(lawyer.currentCases * 2.5),
      earnings: Math.floor(lawyer.currentCases * lawyer.hourlyRate * 2.5)
    };
    
    const recentReviews = Mock.mock({
      'list|0-5': [
        {
          'id|+1': 1,
          'caseId|1000-2000': 1500,
          'caseTitle': '@ctitle(10, 20)',
          'rating|1-5': 5,
          'review': '@cparagraph(1, 2)',
          'reviewerName': '@cname',
          'reviewedAt': '@datetime'
        }
      ]
    }).list;
    
    return [200, {
      code: 200,
      data: {
        lawyer,
        todayCases,
        weeklyStats,
        recentReviews,
        schedule: lawyer.schedule
      }
    }];
  });

  // 获取律师案件列表
  mock.onGet(/\/lawyers\/\d+\/cases/).reply(config => {
    const lawyerId = config.url.split('/').pop();
    const { status, page = 1, size = 10 } = config.params;
    
    // 模拟该律师的案件数据
    const lawyerCases = Mock.mock({
      'list|10-30': [
        {
          'id|+1': 1000,
          'title': '@ctitle(10, 20)',
          'category': '@pick(["民事纠纷", "刑事辩护", "劳动纠纷", "婚姻家事", "合同纠纷", "知识产权"])',
          'status|0-2': 1,
          'priority|0-2': 1,
          'applicantName': '@cname',
          'applicantPhone': /1[3-9]\d{9}/,
          'createdAt': '@datetime',
          'updatedAt': '@datetime',
          'progress|0-100': 50,
          'budget|1000-50000': 5000
        }
      ]
    }).list;
    
    let filteredCases = [...lawyerCases];
    
    if (status !== undefined) {
      filteredCases = filteredCases.filter(c => c.status === parseInt(status));
    }
    
    const start = (page - 1) * size;
    const end = start + size;
    const paginated = filteredCases.slice(start, end);
    
    return [200, {
      code: 200,
      data: paginated,
      pagination: {
        page: parseInt(page),
        size: parseInt(size),
        total: filteredCases.length,
        totalPages: Math.ceil(filteredCases.length / size)
      }
    }];
  });

  // 获取律师统计信息
  mock.onGet('/lawyers/stats').reply(() => {
    const totalLawyers = mockDatabase.lawyers.length;
    const activeLawyers = mockDatabase.lawyers.filter(l => l.status === 0).length;
    const availableLawyers = mockDatabase.lawyers.filter(l => l.available === 1).length;
    
    const specialtyStats = {};
    const experienceStats = { junior: 0, intermediate: 0, senior: 0 };
    
    mockDatabase.lawyers.forEach(l => {
      l.specialties.forEach(s => {
        specialtyStats[s] = (specialtyStats[s] || 0) + 1;
      });
      
      if (l.experience < 3) experienceStats.junior++;
      else if (l.experience < 8) experienceStats.intermediate++;
      else experienceStats.senior++;
    });
    
    const avgRating = mockDatabase.lawyers
      .reduce((sum, l) => sum + l.rating, 0) / mockDatabase.lawyers.length;
    
    return [200, {
      code: 200,
      data: {
        total: totalLawyers,
        active: activeLawyers,
        available: availableLawyers,
        specialtyStats,
        experienceStats,
        avgRating: Math.round(avgRating * 10) / 10,
        topLawyers: mockDatabase.lawyers
          .sort((a, b) => b.rating - a.rating)
          .slice(0, 5)
      }
    }];
  });

  // 律师评价
  mock.onPost(/\/lawyers\/\d+\/review/).reply(config => {
    const lawyerId = config.url.split('/').pop();
    const { rating, review, caseId } = JSON.parse(config.data);
    
    const lawyer = mockDatabase.lawyers.find(l => l.id == lawyerId);
    
    if (!lawyer) {
      return [404, { code: 404, message: '律师不存在' }];
    }
    
    // 更新律师评分
    const newRating = (lawyer.rating * lawyer.reviewCount + rating) / (lawyer.reviewCount + 1);
    lawyer.rating = Math.round(newRating * 10) / 10;
    lawyer.reviewCount += 1;
    
    return [200, { 
      code: 200, 
      message: '评价提交成功',
      data: {
        lawyerId,
        rating,
        review,
        caseId
      }
    }];
  });

  // 更新律师日程
  mock.onPut(/\/lawyers\/\d+\/schedule/).reply(config => {
    const lawyerId = config.url.split('/').pop();
    const { schedule } = JSON.parse(config.data);
    
    const lawyer = mockDatabase.lawyers.find(l => l.id == lawyerId);
    
    if (!lawyer) {
      return [404, { code: 404, message: '律师不存在' }];
    }
    
    lawyer.schedule = schedule;
    
    return [200, { 
      code: 200, 
      message: '日程更新成功',
      data: lawyer.schedule
    }];
  });
} 